package org.hepeng.workx.mybatis.interceptor;


import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * @author he peng
 */
public abstract class AbstractPageQuerySQLRewriter implements PageQuerySQLRewriter {

    @Override
    public String rewrite(String sql, Long startRow, Integer pageSize) {
        if (StringUtils.isBlank(sql) || Objects.isNull(startRow) || startRow < 0
            || Objects.isNull(pageSize) || pageSize < 0) {
            throw new SQLRewriteException("invalid page query parameter, " +
                    "sql [" + sql + "] , startRow [" + startRow + "] , [" + pageSize + "]");
        }

        try {
            Long endRow = startRow + pageSize;
            return doRewrite(sql, startRow, pageSize, endRow);
        } catch (Exception e) {
            throw new SQLRewriteException("rewrite sql for page query error , sql [" + sql + "]" , e);
        }
    }

    protected abstract String doRewrite(String sql, Long startRow, Integer pageSize, Long endRow) throws Exception;
}
